<template>
  <div class="window"></div>
<!--  <video id="video" autoplay="" playsinline="" src="http://192.168.31.156:8888/main/index.m3u8"></video>-->
</template>

<script>
import Hls from 'hls.js'
export default {
  props: {
    hlsUrl: {
      type: String,
      default: 'http://192.168.110.110:8888'
    },
    container: {
      type: String,
      default: 'window'
    }
  },
  data() {
    return {
      videoDom: {}
    }
  },
  methods: {

  },
  computed: {

  },
  mounted() {
    const create = (video) => {
      // always prefer hls.js over native HLS.
      // this is because some Android versions support native HLS
      // but don't support fMP4s.
      if (Hls.isSupported()) {
        const hls = new Hls({

        });

        hls.on(Hls.Events.ERROR, (evt, data) => {
          console.log('流状态异常 ---', data)
          // if (data.type === Hls.ErrorTypes.MEDIA_ERROR)
          //   hls.recoverMediaError();
          // else if (data.fatal) {
            // hls.destroy();
            // setTimeout(() => create(video), 200);
            // setTimeout(() => {
            //   hls.loadSource(`${this.hlsUrl}/main/index.m3u8` + window.location.search);
            // }, 100)
          // }

          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              // try to recover network error
              console.log('fatal network error encountered, try to recover');
             // video.pause()
              hls.recoverMediaError();
              // setTimeout(() => {
              //   video.play();
              // }, 500)
              break;
            case Hls.ErrorTypes.MEDIA_ERROR:
              console.log('fatal media error encountered, try to recover');
              // video.pause()
              hls.recoverMediaError();
              // setTimeout(() => {
              //   video.play();
              // }, 500)
              break;
            default:
              // cannot recover
              console.log('fatal network error encountered, try to recover');
              // video.pause()
              hls.recoverMediaError();
              // setTimeout(() => {
              //   video.play();
              // }, 500)
              break;
          }
        });

        hls.on(Hls.Events.MEDIA_ATTACHED, () => {
          console.log('hls 拉流', `${this.hlsUrl}/stream/V1/hls.m3u8`)
          hls.loadSource(`${this.hlsUrl}/stream/V1/hls.m3u8`);
        });

        hls.on(Hls.Events.MANIFEST_PARSED, () => {
          // setTimeout(() => {
          //   video.play();
          // }, 3000)

          video.play();
        });

        hls.attachMedia(video);

      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        // since it's not possible to detect timeout errors in iOS,
        // wait for the playlist to be available before starting the stream
        console.log('mpe 推流')
        fetch(`${this.hlsUrl}/stream/V1/hls.m3u8`)
          .then(() => {
            video.src = `${this.hlsUrl}/stream/V1/hls.m3u8`;
            video.play();
          });
      }
    };

    /**
     * Parses the query string from a URL into an object representing the query parameters.
     * If no URL is provided, it uses the query string from the current page's URL.
     *
     * @param {string} [url=window.location.search] - The URL to parse the query string from.
     * @returns {Object} An object representing the query parameters with keys as parameter names and values as parameter values.
     */
    const parseQueryString = (url) => {
      const queryString = (url || window.location.search).split("?")[1];
      if (!queryString) return {};

      const paramsArray = queryString.split("&");
      const result = {};

      for (let i = 0; i < paramsArray.length; i++) {
        const param = paramsArray[i].split("=");
        const key = decodeURIComponent(param[0]);
        const value = decodeURIComponent(param[1] || "");

        if (key) {
          if (result[key]) {
            if (Array.isArray(result[key])) {
              result[key].push(value);
            } else {
              result[key] = [result[key], value];
            }
          } else {
            result[key] = value;
          }
        }
      }

      return result;
    };

    /**
     * Parses a string with boolean-like values and returns a boolean.
     * @param {string} str The string to parse
     * @param {boolean} defaultVal The default value
     * @returns {boolean}
     */
    const parseBoolString = (str, defaultVal) => {
      const trueValues = ["1", "yes", "true"];
      const falseValues = ["0", "no", "false"];
      str = (str || "").toString();

      if (trueValues.includes(str.toLowerCase())) {
        return true;
      } else if (falseValues.includes(str.toLowerCase())) {
        return false;
      } else {
        return defaultVal;
      }
    };

    /**
     * Sets video attributes based on query string parameters or default values.
     *
     * @param {HTMLVideoElement} video - The video element on which to set the attributes.
     */
    const setVideoAttributes = (video) => {
      let qs = parseQueryString();

      video.controls = parseBoolString(qs["controls"], false);
      video.muted = parseBoolString(qs["muted"], true);
      video.autoplay = parseBoolString(qs["autoplay"], true);
      video.playsInline = parseBoolString(qs["playsinline"], true);
    };

    /**
     *
     * @param {(video: HTMLVideoElement) => void} callback
     * @param {HTMLElement} container
     * @returns
     */
    const initVideoElement = (callback, container) => {
      console.log('初始化video')
      const video = document.createElement("video");
      video.id = "video-client-bg";

      setVideoAttributes(video);
      container.append(video);
      this.videoDom = video
      callback(video);
    };

    this.$nextTick(() => {
      const body = document.querySelector(`.${this.container}`)
      console.log('body ---', body, this.container)
      initVideoElement(create, body)
    })

  }
}
</script>

<style>
#video-client-bg{
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  object-fit: fill;
}
</style>
